from django.shortcuts import render
from rest_framework.generics import ListAPIView, RetrieveAPIView, GenericAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
import datetime

from apps.activitys.models import Gathering
from apps.activitys.serializers import GatheringsSerializer, GatherSerializerSimple


# Create your views here.


# 获取活动列表
class GatheringsModelViewSet(APIView):
    def get(self, request):
        queryset = Gathering.objects.all()

        count = Gathering.objects.all().count()
        next = ''
        previous = ''
        serializer = GatheringsSerializer(instance=queryset, many=True)
        results = serializer.data
        return Response({
            'count': count,
            'next': next,
            'previous': previous,
            'results': results
        })


# 活动详情
class DetailsAPIView(RetrieveAPIView):
    queryset = Gathering.objects.filter(state=1)
    serializer_class = GatheringsSerializer


# 报名活动
class GatherJoinView(GenericAPIView):
    queryset = Gathering.objects.filter(state=1)
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):

        user = request.user
        gathering = self.get_object()
        # 获取当前时间
        date = datetime.datetime.now()
        # 结束时间
        endtime = gathering.endrolltime.replace(tzinfo=None)
        # 判断当结束时间是否小于当前时间
        # 如果小于报名截止
        if endtime < date:
            return Response({'success': False, 'message': '报名时间已过'}, status=400)
        else:
            # 如果用户名是否存在
            if user in gathering.users.all():
                gathering.users.remove(user)
                gathering.save()
                return Response({'success': True, 'message': '取消成功'})
            else:
                gathering.users.add(user)
                gathering.save()
                return Response({'success': True, 'message': '参加成功'})


# class GatheringJoinView(APIView):
#     def post(self, request, pk):
#         gathering = Gathering.objects.get(id=pk)
#         now_datetime = datetime.datetime.now()
#
#         if now_datetime > gathering.endrolltime:
#             return Response({'success': False, 'message': '报名时间已过'})
#         user = request.user
#         if user in gathering.users.all():
#             gathering.users.remove(user)
#             return Response({'success': True, 'message': '取消成功'})
#         gathering.users.add(user)
#         return Response({'success': True, 'message': '参加成功'})
